package com.myapp.ruyixing.http;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.myapp.ruyixing.utils.LogUtils;

public abstract class RYHttpResponseHandler extends JsonHttpResponseHandler {

	protected String TAG = "RYHttpResponseHandler";
	
	RYJSONParser parser;

	JSONException jsonException = new JSONException("服务器错误");

	@Override
	public final void onSuccess(JSONArray arg0) {
		LogUtils.LOGD(TAG, arg0.toString());
		super.onSuccess(arg0);

		try {
			Object o = parser.parse(arg0);

			if (o != null) {
				onSuccess(o);
			} else {
				onFailure(jsonException, arg0);
			}
		} catch (Exception e) {
			e.printStackTrace();
			onFailure(e);
		}
	}

	@Override
	public final void onSuccess(JSONObject arg0) {
		LogUtils.LOGD(TAG, arg0.toString());
		super.onSuccess(arg0);

		try {
			Object o = parser.parse(arg0);

			if (o != null) {
				onSuccess(o);
			} else {
				onFailure(jsonException, arg0);
			}
		} catch (Exception e) {
			e.printStackTrace();
			onFailure(e);
		}
	}

	public final void setParser(RYJSONParser parser) {
		this.parser = parser;
	}

	public abstract void onSuccess(Object o);

	public abstract void onFailure(Throwable throwable);

	@Override
	public void onFailure(Throwable arg0, JSONArray arg1) {
		super.onFailure(arg0, arg1);

		LogUtils.LOGD(TAG, arg0.toString());
		onFailure(arg0);
	}

	@Override
	public void onFailure(Throwable arg0, JSONObject arg1) {
		super.onFailure(arg0, arg1);

		LogUtils.LOGD(TAG, arg0.toString());
		onFailure(arg0);
	}
}
